﻿using Microsoft.AspNetCore.Components;
using NewLife.Reflection;
using SageKing.Core.Contracts;
using SageKing.Database.Contracts;

namespace SageKing.UI.Blazor.SageKingAntDesign.Contracts;

public interface IAddEdit<T, K>
    where T : IEntityBaseId<K>, new()

{
    public IAddEdit<T, K> Me { get; }
    public bool IsVersionValidation { get; }

    public IBaseService<T, K> DataService { get; }

    public string Title { get; set; }

    public T model { get; set; }

    public AntDesign.Form<T> form { get; set; }

    #region Action事件类
    /// <summary>
    /// 实体变更事件
    /// </summary>
    public Action<T, ChangedEnum> OnModelChanged { get; set; }

    #endregion
    public async Task<bool> Save()
    {
        if (!form.Validate())
        {
            return false;
        }

        var gettmpid = model.Id;

        bool isAdd = false;
        var actionType = ChangedEnum.Modified;

        if (gettmpid.IsNullOrEmpty())
        {
            isAdd = true;
        }
        else if (gettmpid.GetType().IsInt())
        {
            isAdd = gettmpid.ToInt() <= 0;
        }
        else
        {
            isAdd = gettmpid.IsNullOrEmpty();
        }

        if (isAdd)
        {
            var getSave = await DataService.AddReturnEntityAsync(model);
            model = getSave;
            actionType = ChangedEnum.Added;
        }
        else
        {
            if (IsVersionValidation)
            {
                await DataService.UpdateWithOptLock(model);
            }
            else
            {
                await DataService.Update(model);
            }
        }

        OnModelChanged?.Invoke(model, actionType);
        return true;
    }


    public async Task<bool> Delete(K id)
    {
        var result = await DataService.Delete(id);
        if (result)
        {
            if (model == null)
            {
                model = new T();
                model.Id = id;
            }
            OnModelChanged?.Invoke(model, ChangedEnum.Deleted);
        }
        return result;
    }

    public void Reset()
    {
        model = default(T);
        form.Reset();
    }

    public Task FocusFirst()
    {
        return Task.CompletedTask;
    }
}
